package cn.edu.scau.cmi.crawler.controller;

import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.forwardedUrl;

import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.edu.scau.cmi.crawler.service.LidanEventImportService;
import cn.edu.scau.cmi.crawler.service.ShenlirongEventImportService;
import cn.edu.scau.cmi.crawler.service.ZhangwenzhongEventImportService;
import cn.edu.scau.cmi.crawler.service.ZhangxinlianEventImportService;
import cn.edu.scau.cmi.ema.dao.FoodDAO;
import cn.edu.scau.cmi.ema.domain.Address;
import cn.edu.scau.cmi.ema.domain.Event;
import cn.edu.scau.cmi.ema.domain.Event9ld;
import cn.edu.scau.cmi.ema.domain.Event9slr;
import cn.edu.scau.cmi.ema.domain.Event9zwz;
import cn.edu.scau.cmi.ema.domain.Event9zxl;
import cn.edu.scau.cmi.ema.domain.Food;
import cn.edu.scau.cmi.ema.domain.Foodbatch;
import cn.edu.scau.cmi.ema.domain.Producer;
import cn.edu.scau.cmi.ema.domain.base.CmiPagination;
import cn.edu.scau.cmi.ema.service.base.EntityFactoryService;
import cn.edu.scau.cmi.ema.util.CmiSetUtil;
import cn.edu.scau.cmi.front.controller.FrontCmiEmaController;
import cn.edu.scau.cmi.front.dao.CmiFoodDAO;

/*来自张文众老师、沈立荣老师、李丹老师和张星联老师的数据的导入*/
@Controller
public class Event9ZhangwenzhongShenlirongZhangxinlianLidanImportController extends FrontCmiEmaController{
	
	@Autowired CmiFoodDAO cmiFoodDAO;
	
	@Autowired EntityFactoryService entityFactoryService;
	@Autowired ZhangwenzhongEventImportService zhangwenzhongEventImportService;
	@Autowired ShenlirongEventImportService shenlirongEventImportService;
	@Autowired ZhangxinlianEventImportService zhangxinlianEventImportService;
	@Autowired LidanEventImportService lidanEventImportService;
	
	
	//	批量event9zwz记录导入。
	@RequestMapping(value = "/batchEvent9zwzImportDashboard", method = { RequestMethod.POST, RequestMethod.GET })
	public ModelAndView batchEvent9zwzImportDashboard() {
		ModelAndView mav = new ModelAndView();
		Set<Event9zwz> events = event9zwzDAO.findAllEvent9zwzs();
		Set<Integer> allPrepareImportEventIds = new HashSet<>();
		for(Event9zwz event:events) {
			if(event !=null) {
				allPrepareImportEventIds.add(event.getId());
			}
		}
		int minId = CmiSetUtil.getFirstInstance(events).getId();
		int eventQuantity = events.size();
		mav.addObject("allPrepareImportEventIds", allPrepareImportEventIds);
		mav.addObject("eventQuantity", eventQuantity);
		mav.addObject("minId", minId);

		mav.addObject("entityName", "crawlerfile");
		mav.setViewName("adapter/batchEvent9zwzImportDashboard.jsp");
		return mav;
	}
	
	//	批量event9slr记录导入。
	@RequestMapping(value = "/batchEvent9ldImportDashboard", method = { RequestMethod.POST, RequestMethod.GET })
	public ModelAndView batchEvent9ldImportDashboard() {
		ModelAndView mav = new ModelAndView();
		Set<Event9ld> events = event9ldDAO.findAllEvent9lds();
		Set<Integer> allPrepareImportEventIds = new HashSet<>();
		for(Event9ld event:events) {
			if(event !=null) {
				allPrepareImportEventIds.add(event.getId());
			}
		}
		int minId = CmiSetUtil.getFirstInstance(events).getId();
		int eventQuantity = events.size();
		mav.addObject("allPrepareImportEventIds", allPrepareImportEventIds);
		mav.addObject("eventQuantity", eventQuantity);
		mav.addObject("minId", minId);

		mav.addObject("entityName", "crawlerfile");
		mav.setViewName("adapter/batchEvent9ldImportDashboard.jsp");
		return mav;
	}
	
	//	批量event9slr记录导入。
	@RequestMapping(value = "/batchEvent9slrImportDashboard", method = { RequestMethod.POST, RequestMethod.GET })
	public ModelAndView batchEvent9slrImportDashboard() {
		ModelAndView mav = new ModelAndView();
		Set<Event9slr> events = event9slrDAO.findAllEvent9slrs();
		Set<Integer> allPrepareImportEventIds = new HashSet<>();
		for(Event9slr event:events) {
			if(event !=null) {
				allPrepareImportEventIds.add(event.getId());
			}
		}
		int minId = CmiSetUtil.getFirstInstance(events).getId();
		int eventQuantity = events.size();
		mav.addObject("allPrepareImportEventIds", allPrepareImportEventIds);
		mav.addObject("eventQuantity", eventQuantity);
		mav.addObject("minId", minId);

		mav.addObject("entityName", "crawlerfile");
		mav.setViewName("adapter/batchEvent9slrImportDashboard.jsp");
		return mav;
	}
	
	//	批量event9zwz记录导入。
	@RequestMapping(value = "/batchEvent9zxlImportDashboard", method = { RequestMethod.POST, RequestMethod.GET })
	public ModelAndView batchEvent9zxlmportDashboard() {
		ModelAndView mav = new ModelAndView();
		Set<Event9zxl> events = event9zxlDAO.findAllEvent9zxls();
		Set<Integer> allPrepareImportEventIds = new HashSet<>();
		for(Event9zxl event:events) {
			if(event !=null) {
				allPrepareImportEventIds.add(event.getId());
			}
		}
		int minId = CmiSetUtil.getFirstInstance(events).getId();
		int eventQuantity = events.size();
		mav.addObject("allPrepareImportEventIds", allPrepareImportEventIds);
		mav.addObject("eventQuantity", eventQuantity);
		mav.addObject("minId", minId);

		mav.addObject("entityName", "crawlerfile");
		mav.setViewName("adapter/batchEvent9zxlImportDashboard.jsp");
		return mav;
	}
	
	
	
	
	
	
	
	
	//	单个event9zwz记录导入。
	@RequestMapping(value = "/importEvent9zwz/{event9zwzId}", method = { RequestMethod.POST, RequestMethod.GET })
	public ModelAndView importEvent9zwz(@PathVariable Integer event9zwzId, HttpServletRequest request, @ModelAttribute CmiPagination pagination) {

		ModelAndView mav = new ModelAndView();
		
		Event9zwz event9zwz = event9zwzDAO.findEvent9zwzById(event9zwzId);
		
		zhangwenzhongEventImportService.importEvent(event9zwz);

		mav.addObject("entityName", "crawlerfile");
		mav.setViewName("adapter/importCrawlerfilecolumnDashboard.jsp");
		return mav;
	}
	
	
	
//	http://localhost:8080/ema/batchImportZhangwenzhongEvents
	@ResponseBody
	@RequestMapping(value = "/batchImportZhangwenzhongEvents", method = { RequestMethod.POST, RequestMethod.GET })
	public ModelAndView batchImportZhangwenzhongEvents(@RequestBody Map<String, Integer> prepareImportEventIdsMap) {
		ModelAndView mav = new ModelAndView();
		
		Set<Entry<String, Integer>> entrySet = prepareImportEventIdsMap.entrySet();
		int total = entrySet.size();
		int imported = 0;
		for(Entry<String, Integer> entry : entrySet) {
			Event9zwz event9zwz = event9zwzDAO.findEvent9zwzById(entry.getValue());
			if(event9zwz !=null) {

				if(event9zwz.getImported() == null || !event9zwz.getImported() ) {
					System.out.println();
					System.out.println("************************************************");
					System.out.println("开始导入的事件的id号是：" + event9zwz.getId());
					boolean isImported = zhangwenzhongEventImportService.importEvent(event9zwz);
					if(isImported) {
						System.out.println("++++++" + event9zwz.getName() + "导入成功");
					}else {
						System.out.println("------" + event9zwz.getName() + "没有正常导入");
					}
					
					imported ++;
					System.out.println("***************还需要导入的数量是：" + (total-imported));
				}
			}
		}
		return mav;
	}
	
	@RequestMapping(value = "/updateFoodDescription", method = { RequestMethod.POST, RequestMethod.GET })
	public ModelAndView updateFoodDescription() {
		ModelAndView mav = new ModelAndView();
		StringBuilder sb = new StringBuilder();
		Set<Food> foods = foodDAO.findAllFoods();
		foods.remove(foodDAO.findFoodById(-2));
		
		for(Food food : foods) {
			StringBuilder description = new StringBuilder();
			String foodName = food.getName();
//			description.append(foodName);
			
			if(food.getProducer().getId() != -2) {
				description = description.append(food.getProducer().getName());
				food.setDescription(description.toString());
				food = foodService.saveFood(food);
				System.out.println("食物id:" + food.getId() + food.getName() + "的description已经修改");
				continue;
			}
			
			Set<Foodbatch> foodbatchs = food.getFoodbatchsForFood();
			Set<Address> sourceAddresss =  new HashSet<Address>();
			Set<Address> discoveryAddresss =  new HashSet<Address>();
			
			for(Foodbatch foodbatch : foodbatchs) {
				Set<Event> events = foodbatch.getEventsForFoodbatch();
				for(Event event : events) {
					Address sourceAddress = event.getSourceAddress();
					Address discoveryAddress = event.getDiscoveryAddress();
					sourceAddresss.add(sourceAddress);
					discoveryAddresss.add(discoveryAddress);

				}
			}
			
			switch(sourceAddresss.size()) {
			case 0:
				description.append("000000没有生产商，来源地址也没有，这个食物目前没有使用，应该是多余的记录");
				break;
			case 1:
				if(CmiSetUtil.getFirstInstance(sourceAddresss).getId() != -2) {
					description.append("没有生产商，来源地址是" + CmiSetUtil.getFirstInstance(sourceAddresss).getName());
				}else if(discoveryAddresss.size() == 0){
					description.append("没有生产商，来源地址是空, 发现地址也是空");
				}else if(discoveryAddresss.size() == 1){
					description.append("没有生产商，来源地址是空, 发现地址是" + CmiSetUtil.getFirstInstance(discoveryAddresss).getName());
				}else {
					description.append("nnnnnn没有生产商，来源地址是空, 发现地址有多个，不正确");
				}
				
				break;
			default:
				description.append("nnnnnn没有生产商，来源地址数量多于一个，这个食物应该拆分");
			}
			
			food.setDescription(description.toString());
			System.out.println("食物id:" + food.getId() + food.getName() + "的description已经修改");
			
			foodService.saveFood(food);
		}
		return mav;
	}
	
	
	
	@RequestMapping(value = "/checkFoods", method = { RequestMethod.POST, RequestMethod.GET })
	public ModelAndView checkFoods() {
		ModelAndView mav = new ModelAndView();
		StringBuilder sb = new StringBuilder();
		
		Set<Food> foods = foodDAO.findAllFoods();
		for(Food food : foods) {
			String foodName = food.getName();
			Producer producer = food.getProducer();
//			有生厂商
			if(producer.getId() != -2) {
				Set<Food> fs = cmiFoodDAO.findFoodsByNameAndProducer(foodName, producer.getName());
				if(fs.size() > 1) {
					System.out.println("******，id：" + food.getId() + "，食物名称：" + food.getName() + "，生产商：" + food.getProducer().getName() + "数据重复");
				}else {
					System.out.println("VVVVVV，id：" + food.getId() + "，食物名称：" + food.getName() + "，生产商：" + food.getProducer().getName() + "数据正确");
				}
//				continue;
			
			}else {
//			没有生产商
				Set<Foodbatch> foodbatchs = food.getFoodbatchsForFood();
				Set<Address> sourceAddresses = new HashSet<Address>();
//				Set<Address> discoveryAddresses = new HashSet<Address>();
				
				for(Foodbatch fb :foodbatchs) {
					Set<Event> es = fb.getEventsForFoodbatch();
					for(Event event :es) {
						sourceAddresses.add(event.getSourceAddress());
//						discoveryAddresses.add(event.getDiscoveryAddress());
					}
				}
				
				switch(sourceAddresses.size()) {
				case 0 : 
					System.out.println("VVVVVV，id：" + food.getId() + "，食物名称：" + food.getName() + "没有来源地址 ，食物正确");
//					switch(discoveryAddresses.size()) {
//					case 0 : 
//						System.out.println("VVVVVV，id：" + food.getId() + "，食物名称：" + food.getName() +"没有开源地址，也没有发现地址");
//						break;
//						
//					case 1 : 
//						System.out.println("VVVVVV，id：" + food.getId() + "，食物名称：" + food.getName() + "发现地址" + CmiSetUtil.getFirstInstance(discoveryAddresses).getName() + "，食物正确");
//						break;
//						
//					default: 
//						System.out.println("******，id：" + food.getId() + "，食物名称：" + food.getName() + "没有来源地址，发现地址有多个，，食物不正确");
//						break;
//					}
					break;
//					
				case 1 : 
					System.out.println("VVVVVV，id：" + food.getId() + "，食物名称：" + food.getName() + "来源地址" + CmiSetUtil.getFirstInstance(sourceAddresses).getName() + "，食物正确");
					break;
				
				default:
					System.out.println("******，id：" + food.getId() + "，食物名称：" + food.getName() + "来源地址有多个，食物不正确");
					break;
					
				}
			}
		}
		System.out.println("OK");

		
		return mav;
	}
	
	
	
	@ResponseBody
	@RequestMapping(value = "/batchImportZhangxinlianEvents", method = { RequestMethod.POST, RequestMethod.GET })
	public ModelAndView batchImportZhangxinlianEvents(@RequestBody Map<String, Integer> prepareImportEventIdsMap) {
		ModelAndView mav = new ModelAndView();
		
		Set<Entry<String, Integer>> entrySet = prepareImportEventIdsMap.entrySet();
		int total = entrySet.size();
		int imported = 0;
		for(Entry<String, Integer> entry : entrySet) {
			Event9zxl event9zxl = event9zxlDAO.findEvent9zxlById(entry.getValue());
			if(event9zxl !=null) {

				if(event9zxl.getImported() == null || !event9zxl.getImported() ) {
					System.out.println();
					System.out.println("************************************************");
					System.out.println("开始导入的事件的id号是：" + event9zxl.getId());
					boolean isImported = zhangxinlianEventImportService.importEvent(event9zxl);
					if(isImported) {
						System.out.println("++++++" + event9zxl.getName() + "导入成功");
					}else {
						System.out.println("------" + event9zxl.getName() + "没有正常导入");
					}
					imported ++;
					System.out.println("***************还需要导入的数量是：" + (total-imported));
				}
			}
		}
		return mav;
	}
	
	@ResponseBody
	@RequestMapping(value = "/batchImportLidanEvents", method = { RequestMethod.POST, RequestMethod.GET })
	public ModelAndView batchImportLidanEvents(@RequestBody Map<String, Integer> prepareImportEventIdsMap) {
		ModelAndView mav = new ModelAndView();
		
		Set<Entry<String, Integer>> entrySet = prepareImportEventIdsMap.entrySet();
		int total = entrySet.size();
		int imported = 0;
		
		for(Entry<String, Integer> entry : entrySet) {
			Event9ld event9ld = event9ldDAO.findEvent9ldById(entry.getValue());
			if(event9ld !=null) {

				if(event9ld.getImported() == null || !event9ld.getImported() ) {
					System.out.println();
					System.out.println("************************************************");
					System.out.println("开始导入的事件的id号是：" + event9ld.getId());
					boolean isImported = lidanEventImportService.importEvent(event9ld);
					if(isImported) {
						System.out.println("++++++李丹的数据Id:" + event9ld.getId() + "，名称：" + event9ld.getName() + "导入成功");
					}else {
						System.out.println("------李丹的数据Id:" + event9ld.getId() + "，名称：" + event9ld.getName() + "没有正常导入");
					}
					imported ++;
					
					System.out.println("***************还需要导入的数量是：" + (total-imported));
					
				}
			}
			
			System.out.println("***************指定数量李丹的数据导入完成");
			
		}
		return mav;
	}
	
	@ResponseBody
	@RequestMapping(value = "/batchImportShenlirongEvents", method = { RequestMethod.POST, RequestMethod.GET })
	public ModelAndView batchImportShenlirongEvents(@RequestBody Map<String, Integer> prepareImportEventIdsMap) {
		ModelAndView mav = new ModelAndView();
		
		Set<Entry<String, Integer>> entrySet = prepareImportEventIdsMap.entrySet();
		
		int total = entrySet.size();
		int imported = 0;
		for(Entry<String, Integer> entry : entrySet) {
			Event9slr event9slr = event9slrDAO.findEvent9slrById(entry.getValue());
			if(event9slr !=null) {

				if(event9slr.getImported() == null || !event9slr.getImported() ) {
					System.out.println();
					System.out.println("************************************************");
					System.out.println("开始导入的事件的id号是：" + event9slr.getId());
					boolean isImported = shenlirongEventImportService.importEvent(event9slr);
					if(isImported) {
						System.out.println("++++++" + event9slr.getName() + "导入成功");
					}else {
						System.out.println("------" + event9slr.getName() + "没有正常导入");
					}
					
					imported ++;
					System.out.println("***************还需要导入的数量是：" + (total-imported));
				}
			}
		}
		return mav;
	}
	
	
	
	
	
	@RequestMapping(value = "/importEvent9slr/{event9slrId}", method = { RequestMethod.POST, RequestMethod.GET })
	public ModelAndView importEvent9slr(@PathVariable Integer event9slrId, HttpServletRequest request, @ModelAttribute CmiPagination pagination) {

		ModelAndView mav = new ModelAndView();
		
		Event9slr event9slr = event9slrDAO.findEvent9slrById(event9slrId);
		shenlirongEventImportService.importEvent(event9slr);

		mav.addObject("entityName", "crawlerfile");
		mav.setViewName("adapter/importCrawlerfilecolumnDashboard.jsp");
		return mav;
	}
	
	@RequestMapping(value = "/importEvent9zxl/{event9zxlId}", method = { RequestMethod.POST, RequestMethod.GET })
	public ModelAndView importEvent9zxl(@PathVariable Integer event9zxlId, HttpServletRequest request, @ModelAttribute CmiPagination pagination) {

		ModelAndView mav = new ModelAndView();
		
		Event9zxl event9zxl = event9zxlDAO.findEvent9zxlById(event9zxlId);
		zhangxinlianEventImportService.importEvent(event9zxl);

		mav.addObject("entityName", "crawlerfile");
		mav.setViewName("adapter/importCrawlerfilecolumnDashboard.jsp");
		return mav;
	}
	
	@RequestMapping(value = "/importEvent9ld/{event9ldId}", method = { RequestMethod.POST, RequestMethod.GET })
	public ModelAndView importEvent9ld(@PathVariable Integer event9ldId, HttpServletRequest request, @ModelAttribute CmiPagination pagination) {

		ModelAndView mav = new ModelAndView();
		
		Event9ld event9ld = event9ldDAO.findEvent9ldById(event9ldId);
		lidanEventImportService.importEvent(event9ld);

		mav.addObject("entityName", "crawlerfile");
		mav.setViewName("adapter/importCrawlerfilecolumnDashboard.jsp");
		return mav;
	}

}